package com.xjscrm.console.chat.utils;

import com.xjscrm.console.chat.core.ChatMsgHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mingyang.chen create in 2023/4/25 17:22
 */
@Component
public class RMsgHandlerHolder implements ApplicationContextAware {

    private static final Map<Integer, ChatMsgHandler> handlerCache = new ConcurrentHashMap<>();

    // 匹配处理器
    public static ChatMsgHandler matchProcessor(Integer msgTriggerTaskType) {
        return handlerCache.get(msgTriggerTaskType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ChatMsgHandler> msgTriggerTaskProcessorCache = applicationContext.getBeansOfType(ChatMsgHandler.class);

        for (ChatMsgHandler value : msgTriggerTaskProcessorCache.values()) {
            if (Objects.isNull(value.msgType())) {
                throw new IllegalArgumentException("msgType for RMsgHandler required");
            }
            handlerCache.put(value.msgType().getCode(), value);
        }
    }
}
